import collections
class Solution(object):
    def loudAndRich(self, richer, quiet):
        n = len(quiet)
        p = [-1] * n
        quiet = [[quiet[i], i] for i in range(n)]
        quiet.sort()
        d = collections.defaultdict(set)
        for r in richer:
            d[r[0]].add(r[1])
        for i in range(n):
            if p[quiet[i][1]] == -1:
                p[quiet[i][1]] = quiet[i][1]
                now = {quiet[i][1]}
                while now:
                    node = now.pop()
                    for v in d[node]:
                        if p[v] == -1:
                            p[v] = quiet[i][1]
                            now.add(v)
        return p




data = Solution()
richer = [[1, 0], [2, 1], [3, 1], [3, 7], [4, 3], [5, 3], [6, 3]]
quiet = [3, 2, 5, 4, 6, 1, 7, 0]
print(data.loudAndRich(richer, quiet))
